package com.jy.wms.service;

import com.jy.wms.common.base.BaseService;
import com.jy.wms.common.base.ServiceException;
import com.jy.wms.common.base.SucessException;
import com.jy.wms.dao.WmsQualityInspectionListMapper;
import com.jy.wms.dao.WmsStockMapper;
import com.jy.wms.pojo.*;
import com.jy.wms.dao.WmsQualityInspectionListDetailedMapper;
import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
    * @ClassName: WmsQualityInspectionListDetailedService.java
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @Author Jane
    * @Date Mon Nov 06 14:48:21 CST 2017
    */

    @Service
    public class WmsQualityInspectionListDetailedService extends BaseService<WmsQualityInspectionListDetailedMapper,WmsQualityInspectionListDetailed> {
        @Autowired
        private WmsQualityInspectionListMapper wmsQualityInspectionListMapper;
        @Autowired
        private WmsStockMapper wmsStockMapper;
        /**
     * 质量检验_Jane
     * @param map 实体对象
     * @return int
     */
     @Transactional
    public void addZljy(Map<String,Object> map)throws Exception {
         String zjdid = map.get("sszjdid").toString();
         WmsQualityInspectionList w = wmsQualityInspectionListMapper.baseSelectByPrimaryKey(zjdid);
         if ("0".equals(w.getZt()) && w.getCkrwzt()==3){
             //更新质检样品数量和质检状态
             if (map.containsKey("detailed")) {
                 List<Map<String, Object>> list = JSONArray.fromObject(map.get("detailed"));

                 if (list.size() > 0) {
                     WmsQualityInspectionListDetailed detailed = null;
                     WmsEstimatedArrivalOrderDetailed orderDetailed = null;
                     WmsStock stock = null;
                     for (Map<String, Object> map1 : list) {
                         orderDetailed = new WmsEstimatedArrivalOrderDetailed();
                         detailed = new WmsQualityInspectionListDetailed();
                         stock = new WmsStock();
                         detailed.setId(map1.get("id").toString());
                         detailed.setYpsl(Integer.parseInt(map1.get("ypsl").toString()));
                         detailed.setZt(map1.get("zt").toString());
                         dao.baseUpdateYpslByPrimaryKeySelective(detailed);
                         orderDetailed.setId(map1.get("asnmxid").toString());
                         if ("1".equals(map1.get("zt").toString())) {
                             stock.setZjzt(1);//合格
                             orderDetailed.setZjzt("2");//质检合格
                         } else if ("2".equals(map1.get("zt").toString())) {
                             orderDetailed.setZjzt("3");//质检不合格
                             stock.setZjzt(2);//质检不合格
                         } else {
                             stock.setZjzt(0);//初始状态
                             orderDetailed.setZjzt("1");//创建状态
                         }
                         stock.setGlyqmxid(map1.get("asnmxid").toString());
                         wmsStockMapper.updateByGlyqmxid(stock);//更改库存中的质检状态
                         dao.baseUpdateASNMXByPrimaryKeySelective(orderDetailed);//更新质检明细状态
                     }
                     //更新质检人和质检时间
                     List<WmsQualityInspectionListDetailed> qualityDetailed = dao.baseSelectBySszjdid(zjdid);
                     int cs = 0;
                     int zj = 0;
                     for (WmsQualityInspectionListDetailed d : qualityDetailed) {
                         if ("0".equals(d.getZt())) {
                             cs = 1;
                         } else {
                             zj = 1;
                         }
                     }
                     WmsQualityInspectionList quality = new WmsQualityInspectionList();
                     if (cs == 0 && zj == 1) {
                         //全部质检
                         quality.setZt("2");
                     } else if (cs == 1 && zj == 1) {
                         //部分质检
                         quality.setZt("1");
                     } else {
                         //初始状态
                         quality.setZt("0");
                     }
                     quality.setId(zjdid);
                     quality.setZjr(map.containsKey("zjr") ? map.get("zjr").toString() : "");
                     Date date = new Date(Long.valueOf(map.get("zjsj").toString()));
                     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                     quality.setZjsj(format.format(date));
                     dao.baseUpdateZjdztByPrimaryKeySelective(quality);
                     //更新ASN单据质检状态
                     if (map.containsKey("asnid")) {
                         List<WmsEstimatedArrivalOrderDetailed> arr = dao.baseSelectASNMXByPrimaryKey(map.get("asnid").toString());
                         if (arr.size() > 0) {
                             int cjAsn = 0;
                             int zjAsn = 0;
                             for (WmsEstimatedArrivalOrderDetailed a : arr) {
                                 if ("1".equals(a.getZjzt())) {
                                     cjAsn = 1;
                                 } else if (!"0".equals(a.getZjzt())) {
                                     zjAsn = 1;
                                 }
                             }
                             WmsEstimatedArrivalOrder o = new WmsEstimatedArrivalOrder();
                             if (cjAsn == 0 && zjAsn == 1) {
                                 o.setZjzt("3");
                             } else if (cjAsn == 1 && zjAsn == 1) {
                                 o.setZjzt("2");
                             } else if (cjAsn == 1 && zjAsn == 0) {
                                 o.setZjzt("1");
                             }
                             o.setId(map.get("asnid").toString());
                             dao.baseUpdateASNZJZTByPrimaryKeySelective(o);
                         }
                     }

                 } else {
                     throw new ServiceException("质量检验失败，无质检单明细被检验");
                 }
                 //根据质检单ID查询质检明细判断是否质检完成
                 List<WmsQualityInspectionListDetailed> inspection = dao.baseSelectByZjdid(zjdid);
                 int wc = 0;
                 int bwc = 0;
                 for (WmsQualityInspectionListDetailed d : inspection) {
                     if (Integer.parseInt(d.getYjsl()) - d.getYpsl() == 0) {
                         wc = 1;
                     } else if (Integer.parseInt(d.getYjsl()) - d.getYpsl() > 0) {
                         bwc = 1;
                     }
                 }
                 WmsQualityInspectionList quality = new WmsQualityInspectionList();
                 WmsEstimatedArrivalOrder est = new WmsEstimatedArrivalOrder();
                 if (wc == 1 && bwc == 0) {
                     quality.setZt("3");
                     quality.setId(zjdid);
                     dao.baseUpdateZjdztByPrimaryKeySelective(quality);
                     est.setZjzt("4");
                     est.setId(map.get("asnid").toString());
                     dao.baseUpdateASNZJZTByPrimaryKeySelective(est);
                 }
                 //根据ASN明细Id修改po合格率
                 if (map.containsKey("asnid")) {
                     List<WmsEstimatedArrivalOrderDetailed> arr = dao.baseSelectASNMXByPrimaryKey(map.get("asnid").toString());
                     if (arr.size() > 0) {
                         for(WmsEstimatedArrivalOrderDetailed estd:arr){
                             if(!("0".equals(estd.getDycgmxid()))) {
                                 Integer hgsl = dao.seachHgslByDycgmxid(estd.getDycgmxid());//记录合格数量
                                 WmsPurchaseOrderDetailed pod = dao.seachPoyqslByDycgmxid(estd.getDycgmxid());//获取PO明细的预期数量
                                 BigDecimal f1 = new BigDecimal((float) hgsl / Integer.parseInt(pod.getSl())).setScale(2, BigDecimal.ROUND_HALF_UP);
                                 WmsPurchaseOrderDetailed podetailed = new WmsPurchaseOrderDetailed();
                                 podetailed.setId(estd.getDycgmxid());
                                 podetailed.setHgl(f1);
                                 dao.updateHglByDycgmxid(podetailed);
                             }
                         }
                     }
                     }
             } else {
                 throw new ServiceException("质量检验失败，无质检单明细传入");
             }
     }else{
        throw new ServiceException("质量检验失败，质检状态不符合");
    }
    }

   /**
    * 插入一条记录（匹配有值的字段）
    * @param entity 实体对象
    * @return int
    */
    public Integer baseInsertSelective( WmsQualityInspectionListDetailed entity){
         return dao.baseInsertSelective( entity);
    }

   /**
    * 删除（根据主键ID删除）
    * @param id 主键
    * @return int
    */
    public Integer baseDeleteByPrimaryKey( String id){
         return dao.baseDeleteByPrimaryKey( id);
    }

   /**
    * 删除（根据ID 批量删除）
    * @param idList 主键ID列表
    * @return int
    */
    public Integer baseDeleteBathPrimaryKeys( List<String> idList){
         return dao.baseDeleteBathPrimaryKeys( idList );
    }

    /**
    * 分页查询
    * @param entity 实体
    * @return Page<WmsQualityInspectionListDetailed>
    */
    public Page<WmsQualityInspectionListDetailed> baseSelectPage(WmsQualityInspectionListDetailed entity ){
        PageHelper.startPage(entity.getPage(),entity.getRows());
        return (Page<WmsQualityInspectionListDetailed>)dao.baseSelectPage( entity );
    }

   /**
    * 查询（根据主键ID查询）
    * @param id 主键ID
    * @return WmsQualityInspectionListDetailed
    */
    public WmsQualityInspectionListDetailed baseSelectByPrimaryKey( String id ){
         return dao.baseSelectByPrimaryKey( id );
    }

   /**
    * 查询（根据ID 批量查询）
    * @param idList 主键ID列表
    * @return list
    */
    public Integer baseSelectBathPrimaryKeys( List<WmsQualityInspectionListDetailed> idList ){
         return dao.baseSelectBathPrimaryKeys( idList );
    }

   /**
    *修改质检单_Jane（匹配有值的字段）
    * @param entity 主键ID列表
    * @return int
    */
    public void baseUpdateByPrimaryKeySelective( List<WmsQualityInspectionListDetailed> entity)throws Exception{
               WmsQualityInspectionList list= wmsQualityInspectionListMapper.baseSelectByPrimaryKey(entity.get(0).getSszjdid());
            if(list!=null){
                if(list.getCkrwzt()==0){
                    for(WmsQualityInspectionListDetailed detailed:entity){
                        dao.baseUpdateYpslByPrimaryKeySelective(detailed);
                    }
                }else{
                    throw new ServiceException("此质检单已创建任务不能再修改");
                }
            }else{
                throw new ServiceException("此质检单不存在异常");
            }
    }

   /**
    *修改（根据主键ID修改）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKey( WmsQualityInspectionListDetailed entity){
         return dao.baseUpdateByPrimaryKey( entity);
    }
        /**
         *查询（根据质检单ID列表查询）_Jane
         * @param sszjdid 所属质检单ID
         * @return int
         */
      public List<WmsQualityInspectionListDetailed>  baseSelectMxBySszjdid(String sszjdid){
        return dao.baseSelectMxBySszjdid(sszjdid);
      }
}
